package nl.vu.few.ibivu.biomodels.client.event;

import nl.vu.few.ibivu.biomodels.shared.UserInfo;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;

public class LoginStateChangedEvent extends GwtEvent<LoginStateChangedEventHandler> {
	private enum State {
		LOGIN, LOGOUT
	}
	
	private final UserInfo userInfo;
	private final State status;
	
	public static Type<LoginStateChangedEventHandler> TYPE = new Type<LoginStateChangedEventHandler>();

	public LoginStateChangedEvent(UserInfo userInfo) {
		this.userInfo = userInfo;
		this.status = userInfo.isLoggedIn() ? State.LOGIN : State.LOGOUT;
	}

	@Override
	public com.google.gwt.event.shared.GwtEvent.Type<LoginStateChangedEventHandler> getAssociatedType() {
		return TYPE;
	}

	@Override
	protected void dispatch(LoginStateChangedEventHandler handler) {
		if (status == State.LOGIN) {
			handler.onUserLogin(this);
		} else {
			handler.onUserLogout(this);
		}
	}

	public static HandlerRegistration register(EventBus eventBus, LoginStateChangedEventHandler handler) {
		return eventBus.addHandler(TYPE, handler);
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

}
